import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/index'
// import router from '@/router'
// import { removeToken } from '@/utils/auth'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    const token = store.getters.token
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => { // 状态码2xx，3xx走这里
    if (response.data.success) { return response } else {
      Message({
        type: 'error',
        message: response.data.message
      })
      return Promise.reject(response.data.message)
    }
  },
  error => { // 4xx,5xx走这里
    if (error.response.data.code === 10002) {
      store.dispatch('user/logoutActions')
    } else {
      Message({
        type: 'error',
        message: error
      })
    }

    return Promise.reject(error)
  }
)

export default service
